from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from random import randint
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken
import pickle, base64
from celery_tasks.sms.tasks import send_sms_code
from goods.models import SKU
from goods.serializers import SKUSerializers
from user.models import User
from user.serializers import UserSerializer, UserDetailSerializer, UserEmailSerializer, VerifyEmailSerializer, \
    AddUserBrowsingHistorySerializer
from rest_framework.permissions import IsAuthenticated
from carts.utils import merge_cart_cookie_redis



# Create your views here.


class SMSCodeView(APIView):

    def get(self, request, mobile):
        """
        发送短信验证码
        :param request:
        :param mobile:
        :return:
        """
        # 判断60s
        # 建立连接
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s'%mobile)
        if flag:
            return Response({'message': 'error'}, status=401)
        # 生成短信验证码
        sms_code = '%06d'%randint(0, 999999)

        # 保存到reids缓存
        pl = conn.pipeline()
        pl.setex('sms_code_%s'%mobile, 300, sms_code)
        pl.setex('sms_flag_%s'%mobile, 60, 1)
        pl.execute()

        # # 发送短信
        send_sms_code.delay(mobile, sms_code)

        # 返回结果
        return Response({'message':'ok'})


class UserNameView(APIView):

    def get(self, request, username):
        """
        判断用户名注册是否重名
        :param request:
        :param username:
        :return:
        """
        # 查询用户数量
        count = User.objects.filter(username=username).count()
        # 返回查询的数量

        return Response({
            'username': username,
            'count': count,
        })


class MobileView(APIView):

    def get(self, request, mobile):
        """
        判断用户注册手机号是否重复
        :param request:
        :param mobile:
        :return:
        """
        # 查询用户数量
        count = User.objects.filter(mobile=mobile).count()
        # 返回查询的数量

        return Response({
            'mobile': mobile,
            'count': count,
        })


class UserView(CreateAPIView):
    """
    用户点击注册按钮
    """
    serializer_class = UserSerializer


class UserDetailView(RetrieveAPIView):
    """
    用户个人中心数据
    """
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]

    # 重写get_object方法返回指定数据对象
    def get_object(self):

        return self.request.user


class UserEmailView(UpdateAPIView):
    """
    用户添加邮箱
    """
    serializer_class = UserEmailSerializer

    def get_object(self):
        return self.request.user


class VerifyEmailView(GenericAPIView):

    serializer_class = VerifyEmailSerializer

    def get(self, request):

        # 获取用户数据
        data = request.query_params

        # 数据验证
        ser = self.get_serializer(data=data)
        ser.is_valid()

        # 更新用户邮箱状态
        data = ser.validated_data['data']
        id = data['id']
        username = data['username']

        try:
            user = User.objects.get(id=id, username=username)
        except:
            return Response({'errors':'用户不存在'}, status=400)

        user.email_active = True
        user.save()

        # 结果返回
        return Response(data)


class AddUserBrowsingHistoryView(CreateAPIView):
    permission_classes = [IsAuthenticated]

    serializer_class = AddUserBrowsingHistorySerializer

    def get(self, request):

        user = request.user

        conn = get_redis_connection('history')

        sku_id_list = conn.lrange('history_%s'%user.id, 0, 10)

        sku_list = []
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id = sku_id)
            sku_list.append(sku)

        ser = SKUSerializers(sku_list, many=True)

        return Response(ser.data)


class UserAuthorizeView(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):

        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            response = merge_cart_cookie_redis(request, response, user)

        return response











